<?php
/**
 * Created by PhpStorm.
 * User: George
 * Date: 2017/9/25
 * Time: 11:06
 */

namespace AdminBundle\Report;

use AdminBundle\Entity\BaseWebchatUser;

/**
 * 上传联系人信息
 * Class ContactUploadTask
 * @package AdminBundle\Task
 */
class ContactUploadTask extends Task
{
    public function report()
    {
        $task_result = $this->task['result'];

        $member_count = 0;
        if (isset($task_result['wechat']) && !empty($task_result['wechat'])) {

            $member_count = $this->newWebchatUser($task_result['wechat']);
//            $message = sprintf('好友数量:%d', $member_count);
        }

        return $member_count;
    }

    /**
     * 维护完善上传的微信信息，包括成员好友
     * @param $wechat
     * @return int
     */
    private function newWebchatUser(&$wechat)
    {
        if (empty($wechat['username'])) {
            return 0;
        }

        $em = $this->em;
        $webchatUser = $em->getRepository('AdminBundle:BaseWebchatUser')->findOneBy(['userName' => $wechat['username']]);
        if ($webchatUser == null) {
            $webchatUser = new BaseWebchatUser();
            $webchatUser->setCtime(new \DateTime())
                ->setIp($this->ip)
                ->setCreator($this->username)
                ->setUserName($wechat['username'])
                ->setDeviceId($this->device->getId())
                ->setDeviceImei($this->device->getImei())
                ->setDeviceText($this->device->getName());
        }
        // 更新自身信息
        $webchatUser->setNickname($wechat['nickname'])
            ->setMobile($wechat['mobile'])
            ->setSignature($wechat['signature'])
            ->setEmail($wechat['email'])
            ->setHeadImgUrl($wechat['head_img_url'])
            ->setProvince($wechat['province'])
            ->setCity($wechat['city'])
            ->setCountry($wechat['country'])
            ->setSex($wechat['sex']);
        $em->persist($webchatUser);
        $em->flush();

        return $this->newMember($webchatUser->getId(), $wechat['member']);
    }

    /**
     * 成员好友更新，新增
     * @param $webchatId
     * @param $members
     * @return int
     */
    private function newMember($webchatId, &$members)
    {
        $count = 0;
        if (empty($members) || empty($webchatId)) {
            return $count;
        }
        $newContact = new NewContactTask();
        $newContact->setDevice($this->device)
            ->setIp($this->ip)
            ->setUsername($this->username)
            ->setDoctrineManager($this->em)
            ->setTask(['username' => $webchatId, 'new_member' => $members]);

        $count = $newContact->report();

        return $count;
    }

}